<?php
/**
 * User: b179a9
 * Date: 05.09.11
 * Time: 18:31
 */

class MapController extends Zend_Controller_Action
{

    /**
     * @var Lib_Flash
     */
    protected $_flashMessenger = null;

    public function init()
    {
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        } else {
            $this->_helper->layout()->setLayout('pirates-layout');
        }

        $this->_flashMessenger = new Lib_Flash();
        $auth = Zend_Auth::getInstance();
        $data = $auth->getStorage()->read();
        $massiv = (array)$data;

        if (isset($massiv['name'])) $this->view->name = $massiv['name'];
        
        
    }


    function __call($method, $args)
    {
        $this->_forward('index');
    }

    public function viewAction()
    {
        $id = $this->_request->getParam('id');

        $auth = Zend_Auth::getInstance();
        $data = $auth->getStorage()->read();

        $ordersManager = new \Managers\Orders();
        $mapsManager = new \Managers\Map();

        // Если у пользователя есть права на карту.
        if ($ordersManager->hasAccess($data->id, $id)) {
            $map = $mapsManager->isAvailable($id);
            
            if ($map) {
                $this->view->map = $map;
                $answersManager = new \Managers\Answers();


                   $auth = Zend_Auth::getInstance();
                    $data = $auth->getStorage()->read();
                    $massiv = (array)$data;

                    $isAnswer =  $answersManager->isAnswer($massiv['id'],$map['id']);
                    $this->view->isAnswer=$isAnswer;


            } else {
                $this->_flashMessenger->addMessage('This map is not available now. We are sorry.',
                                                   Lib_Flash::WARNING,
                                                   Lib_Flash::POST);
            }

        } else {
            $this->_forward('buy');
        }

    }

    /**
     * Действие покупки карты за виртуальные (внутрисайтные) деньги.
     */
    public function buyAction()
    {
        $id = $this->_request->getParam('id');
        $data = Zend_Auth::getInstance()->getStorage()->read();

        $mapsManager = new \Managers\Map();
        $map = $mapsManager->getById($id);

        if ($this->_request->isPost()) {
            $mapParam = $this->_request->getParam('map');
            try {
                $mapsManager->buy($mapParam, $data->id);
                $this->_flashMessenger->addMessage('You successfully bought the map.', Lib_Flash::NOTICE, Lib_Flash::PRE);
                 $date= date("h:I:s a F d,  Y ");

                    $email=$data->email;
                    $name= $data->nick;
                    $idofuser= $data->id;



                    $datend= $map['dateend']->format('F d,  Y  h:I:s a');
                    $titleofmap=$map['title'];
                    $text = $this->view->render('mail.phtml');
                    $search=array('[Name]','[Email]','[StartTime]','[EndTime]','[TitleofMap]','[ID]');
                    $parameters=array($name,$email,$date,$datend,$titleofmap,$idofuser);
                    $message=str_replace($search,$parameters,$text);
                     $mailManager=new \Managers\Mail();
                     $mailManager->send($name,$email,$message);
                $this->_redirect('/map');
            } catch (Exception $e) {
                $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::PRE);
                $this->_redirect('/map');
            }
        }

         $this->view->map = $map;


    }

    public function indexAction()
    {
        $auth = Zend_Auth::getInstance();
        $data = $auth->getStorage()->read();

        $ordersManager = new \Managers\Orders();
        $orders = $ordersManager->getMaps($data->id);

        $usersManager = new \Managers\Users();
        $user = $usersManager->getById($data->id);

        $this->view->user = $user;
        $this->view->orders = $orders;
        $this->view->pageName = "Discover Treasures";
        $form = new App_Form_Payment_Type();
        $this->view->form = $form;
        


    }

    public function mapsAction()
    {
        $authData = Zend_Auth::getInstance()->getStorage()->read();
        $postal = $authData->postal;

        $map = new \Managers\Map();
        $this->view->map = $map->getAvailable();
        $this->view->pageName = "Treasure Maps";
        $this->view->postal = $postal;

    }

    /**
     * Возвращает текст для отправки по ел.почте после ответа пользователя.
     * @param array $user
     * @param array $map
     * @return string
     */
    private function getAnsweredMessage(array $user, array $map)
    {
        $baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
        $url = $baseUrl . '/answers/' . $map['id'];
        $message = <<<_END
        User {$user['name']} {$user['lastName']} with email {$user['email']} has answered to map {$map['title']}.
        <a href="{$url}"> See all answers to this map. </a>
_END;
        return $message;
    }

    /**
     * Winners
     * Url: /map/report
     * @return void
     */
    public function reportAction()
    {
        $answersManager = new \Managers\Answers();
        $filter = array('correct' => 1);
        $answers =  $answersManager->getList($filter);
        $this->view->answers = $answers;
    }

    function answerAction()
    {
        $id = $this->_request->getParam('id');

        $auth = Zend_Auth::getInstance();
        $data = $auth->getStorage()->read();

        $ordersManager = new \Managers\Orders();
        $mapsManager = new \Managers\Map();

        // Если у пользователя есть права на карту.
        if ($ordersManager->hasAccess($data->id, $id)) {

            $answersManager = new \Managers\Answers();
            $answer = $answersManager->recordExists($data->id, $id);

            if ($mapsManager->isAvailable($id)) {

                $map = $mapsManager->getById($id);

                $this->view->map = $map;

                if ($answer) {
                    $this->_flashMessenger->addMessage('You have already answered to this map.',
                                                       Lib_Flash::NOTICE,
                                                       Lib_Flash::POST);
                } else {
                    //Если получен ответ на карту.
                    if ($this->_request->isPost()) {
                        $user_answer = $this->_request->getParam('answer');
                        $validator = new Zend_Validate_StringLength(array('min' => 1,
                                                                         'max' => 128));
                        if ($validator->isValid($user_answer)) {

                            $correctAnswer = $map['answer'];

                            $user_answer = $answersManager->add($data->id, $id, $user_answer, $correctAnswer);

                            $usersManager = new \Managers\Users();
                            $user = $usersManager->getById($data->id);
                            $message = $this->getAnsweredMessage($user, $map);

                            \Managers\Mail::sendEmail($message, \Managers\Mail::ADMIN, 'Answer received.');
                            $this->_flashMessenger->addMessage('Your answer is accepted', Lib_Flash::NOTICE, Lib_Flash::POST);

                        } else {
                            $this->_flashMessenger->addMessage('Answer must contains more then one symbol and less then 128 symbols');
                            $this->view->form = 1;
                        }
                    } else {
                        $this->view->form = 1;
                    }
                }

            } else {
                $this->_flashMessenger->addMessage('This map is not available now.', Lib_Flash::ERROR, Lib_Flash::POST);
            }

        } else {
            $this->_forward('buy');
        }

    }


}
